# _*_coding:utf-8_*_
"""
   ATS 1.0(Automated Test Server, Version 1.0) Wafer Description File parser,
   Developed by Ivy.Li 2013.03.18.
   (C)Copyright 2013 Hech. All rights reserved
"""
import configparser as ConfigParser
import os

# error messages define
INVAL_HEADER = 21
INVAL_SITES = 22
INVAL_SUBSITES = 23
NO_WDF_FOUND = 24


class WDF:
    """
    header: {
    'Version':'1.0',
    'Date':'14/03/2013',
    'Project':'Single',
    'DiameterUnits':'English'
    'Diameter':12
    'Units':Metric
    ...
    }

    subsites:[(subsite_name,[x,y]),...]
    sites:[(site_name),[x,y]),...]
    ssites_seq[Subsite execution sequence]
    """

    def __init__(self, wdf=None):
        if wdf:
            self.load(wdf)
        else:
            self.clear()

    def clear(self):
        self.header = {}
        self.subsites = []
        self.sites = []
        self.error = 0
        self.ssites_seq = []

    def load(self, wdf):
        if not os.path.exists(wdf):
            self.error = NO_WDF_FOUND
            return
        self.clear()
        cp = ConfigParser.ConfigParser()
        cp.read(wdf)

        try:
            for k, v in cp.items('Header'):
                self.header[k] = v
        except:
            self.error = INVAL_HEADER
            return
        try:
            tmp_dict = {}
            sites_seq = []

            for k, v in cp.items('Sites'):
                if k.lower() == 'sites_seq':
                    if v:
                        sites_seq = v.split(',')
                else:
                    tmp_dict[k] = eval(v)
            print(sites_seq)
            print("*****************************************************")
            for s in sites_seq:
                if s.lower() in tmp_dict:
                    self.sites.append((s, tmp_dict[s.lower()]))
        except:
            self.error = INVAL_SITES
            return
        try:
            tmp_dict = {}
            self.ssites_seq = []
            for k, v in cp.items('Subsites'):
                if k.lower() == 'subites_seq':
                    if v:
                        self.ssites_seq = v.split(',')
                else:
                    tmp_dict[k] = eval(v)

            for ss in self.ssites_seq:
                if ss.lower() in tmp_dict:
                    self.subsites.append((ss, tmp_dict[ss.lower()]))
        except:
            self.error = INVAL_SUBSITES
            return

# Test code
# wdf=WDF(r'H:\MrBig_2013_0311\InputFileFormat\InputFileFormat Revised0318\SubsiteLelvelPrj\p.wdf')
# print(wdf.header)
#
# print(wdf.sites)
# print(wdf.subsites)
# print(wdf.ssites_seq)
